import java.awt.image.BufferedImage;

public class BinaryImageFilter extends AbstractBufferedImageOp {
    @Override
    public BufferedImage filter(BufferedImage src, BufferedImage dest) {
        int width = src.getWidth();
        int height = src.getHeight();

        if (dest == null)
            dest = createCompatibleDestImage(src, null);

        int[] inPixels = new int[width * height];
        int[] outPixels = new int[width * height];
        getRGB(src, 0, 0, width, height, inPixels);
        int index = 0;
        for (int row = 0; row < height; row++) {
            int ta = 0, tr = 0, tg = 0, tb = 0;
            for (int col = 0; col < width; col++) {
                // 读取一个像素的RGB值
                index = row * width + col;
                ta = (inPixels[index] >> 24) & 0xff;
                tr = (inPixels[index] >> 16) & 0xff;
                tg = (inPixels[index] >> 8) & 0xff;
                tb = inPixels[index] & 0xff;

                // 对图像的每个像素点重新计算RGB值
                int fr = (tr < 128) ? 0 : 255;
                int fg = (tg < 128) ? 0 : 255;
                int fb = (tb < 128) ? 0 : 255;



                //outPixels[index] = (clamp(ta) << 24) | (clamp(fr) << 16) | (clamp(fg) << 8) | clamp(fb);
                outPixels[index] = (ta << 24) | (fr << 16) | (fg << 8) | fb;
            }
        }
        setRGB(dest, 0, 0, width, height, outPixels);
        return dest;
    }
}
